/**
 * @author yanwl
 * @date 2015-01-15
 */
package com.chnbst.bstyun.core.common;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

public class OperateImage {
	
	public static String cut(String srcpath,int x,int y,int width,int height) throws IOException {
		String result = "";
		if (srcpath != null) {
			String imageType = srcpath.substring(srcpath.lastIndexOf(".") + 1,
					srcpath.length());
			FileInputStream is = null;
			ImageInputStream iis = null;
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + imageType;
			String str = srcpath.substring(0, srcpath.lastIndexOf("/")+1);
			String subpath = str+newFileName;
			try {
				is = new FileInputStream(srcpath);
				Iterator<ImageReader> it = ImageIO
						.getImageReadersByFormatName(imageType);
				ImageReader reader = it.next();
				iis = ImageIO.createImageInputStream(is);
				reader.setInput(iis, true);
				ImageReadParam param = reader.getDefaultReadParam();
				Rectangle rect = new Rectangle(x, y, width, height);
				param.setSourceRegion(rect);
				BufferedImage bi = reader.read(0, param);
				ImageIO.write(bi, imageType, new File(subpath));
			} finally {
				if (is != null)
					is.close();
				if (iis != null)
					iis.close();
			}
			result = newFileName;
		}else {
			result = "图片路径不能为空";
		}
		return result;
	}

	public static void main(String[] args) throws IOException {
		System.out.println(cut("D:/1.jpg", 0, 0, 500, 600));
	}
}
